import React, { useState, useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import {
  makeStyles,
  Card,
  Button,
  Input,
  Field,
  Dropdown,
  Option,
  Badge,
  DataGrid,
  DataGridHeader,
  DataGridHeaderCell,
  DataGridBody,
  DataGridRow,
  DataGridCell,
  TableColumnDefinition,
  createTableColumn,
  Spinner,
  ToggleButton,
  Menu,
  MenuTrigger,
  MenuPopover,
  MenuList,
  MenuItem,
  Slider,
  Text,
} from '@fluentui/react-components';
import {
  Add20Regular,
  Filter20Regular,
  ArrowDownload20Regular,
  ArrowSync20Regular,
  Grid20Regular,
  List20Regular,
  MoreVertical20Regular,
  Edit20Regular,
  Eye20Regular,
  Delete20Regular,
  Search20Regular,
} from '@fluentui/react-icons';
import { RootState } from '../store/store';
import { Opportunity, setOpportunities, setView, setPagination } from '../store/slices/opportunitySlice';

const useStyles = makeStyles({
  container: {
    display: 'flex',
    flexDirection: 'column',
    gap: '24px',
    height: '100%',
  },
  header: {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: '16px',
  },
  title: {
    fontSize: '24px',
    fontWeight: '600',
    color: '#1D2129',
    margin: 0,
  },
  actions: {
    display: 'flex',
    gap: '12px',
  },
  filterCard: {
    padding: '20px',
  },
  filterRow: {
    display: 'grid',
    gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))',
    gap: '16px',
    alignItems: 'end',
  },
  filterActions: {
    display: 'flex',
    gap: '8px',
  },
  contentCard: {
    flex: 1,
    display: 'flex',
    flexDirection: 'column',
    padding: '0',
    overflow: 'hidden',
  },
  contentHeader: {
    padding: '20px 20px 0',
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  viewToggle: {
    display: 'flex',
    gap: '4px',
  },
  contentBody: {
    flex: 1,
    padding: '20px',
    overflow: 'auto',
  },
  dataGrid: {
    height: '100%',
  },
  kanbanContainer: {
    display: 'flex',
    gap: '16px',
    height: '100%',
    overflowX: 'auto',
    paddingBottom: '16px',
  },
  kanbanColumn: {
    minWidth: '280px',
    backgroundColor: '#F8F9FA',
    borderRadius: '8px',
    padding: '16px',
    display: 'flex',
    flexDirection: 'column',
    gap: '12px',
  },
  kanbanHeader: {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: '8px',
  },
  kanbanTitle: {
    fontSize: '14px',
    fontWeight: '600',
    color: '#1D2129',
  },
  kanbanCount: {
    fontSize: '12px',
    color: '#86909C',
  },
  kanbanCard: {
    backgroundColor: '#FFFFFF',
    border: '1px solid #E5E6EB',
    borderRadius: '6px',
    padding: '12px',
    cursor: 'pointer',
    transition: 'box-shadow 0.2s',
    '&:hover': {
      boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)',
    },
  },
  cardTitle: {
    fontSize: '14px',
    fontWeight: '500',
    color: '#1D2129',
    marginBottom: '8px',
  },
  cardCustomer: {
    fontSize: '12px',
    color: '#86909C',
    marginBottom: '8px',
  },
  cardValue: {
    fontSize: '16px',
    fontWeight: '600',
    color: '#165DFF',
    marginBottom: '8px',
  },
  cardMeta: {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    fontSize: '12px',
    color: '#86909C',
  },
  statusBadge: {
    fontSize: '11px',
  },
  pagination: {
    padding: '16px 20px',
    borderTop: '1px solid #E5E6EB',
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  paginationInfo: {
    fontSize: '14px',
    color: '#86909C',
  },
  paginationControls: {
    display: 'flex',
    gap: '8px',
    alignItems: 'center',
  },
  loadingContainer: {
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    height: '200px',
  },
  emptyState: {
    textAlign: 'center',
    padding: '60px 20px',
    color: '#86909C',
  },
  valueRangeContainer: {
    display: 'flex',
    flexDirection: 'column',
    gap: '8px',
  },
  valueRangeLabel: {
    fontSize: '12px',
    color: '#86909C',
  },
});

const OpportunityListPage: React.FC = () => {
  const classes = useStyles();
  const navigate = useNavigate();
  const dispatch = useDispatch();
  
  const { 
    opportunities, 
    loading, 
    view, 
    pagination 
  } = useSelector((state: RootState) => state.opportunity);

  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState<string[]>([]);
  const [industryFilter, setIndustryFilter] = useState<string[]>([]);
  const [valueRange, setValueRange] = useState<[number, number]>([0, 10000000]);

  // 状态选项
  const statusOptions = [
    { key: 'initial', label: '初步接触', color: '#FF7D00' },
    { key: 'communication', label: '需求沟通', color: '#165DFF' },
    { key: 'proposal', label: '方案制定', color: '#00B42A' },
    { key: 'negotiation', label: '商务谈判', color: '#86909C' },
    { key: 'closed_won', label: '已成单', color: '#00B42A' },
    { key: 'closed_lost', label: '已关闭', color: '#F53F3F' },
  ];

  const industryOptions = [
    '互联网',
    '金融',
    '制造业',
    '医疗',
    '教育',
    '零售',
    '房地产',
    '其他',
  ];

  // 模拟数据加载
  useEffect(() => {
    const loadOpportunities = async () => {
      const mockOpportunities: Opportunity[] = [
        {
          id: '1',
          customerName: '阿里巴巴集团',
          opportunityName: '云计算数字化转型项目',
          value: 12000000,
          status: 'negotiation',
          expectedCloseDate: '2024-09-15',
          owner: '张三',
          industry: '互联网',
          description: '帮助阿里巴巴完成内部系统的云计算转型',
          probability: 75,
          createdAt: '2024-06-01T10:00:00Z',
          updatedAt: '2024-07-20T15:30:00Z',
          contact: {
            name: '李经理',
            phone: '13800138001',
            email: 'li@alibaba.com',
            position: '技术总监',
          },
          progress: [],
        },
        {
          id: '2',
          customerName: '腾讯科技',
          opportunityName: '游戏云服务平台',
          value: 8500000,
          status: 'proposal',
          expectedCloseDate: '2024-08-30',
          owner: '李四',
          industry: '互联网',
          description: '为腾讯游戏提供专业的云服务解决方案',
          probability: 60,
          createdAt: '2024-06-15T09:30:00Z',
          updatedAt: '2024-07-22T11:45:00Z',
          contact: {
            name: '王总',
            phone: '13900139001',
            email: 'wang@tencent.com',
            position: '产品经理',
          },
          progress: [],
        },
        {
          id: '3',
          customerName: '字节跳动',
          opportunityName: '广告系统优化服务',
          value: 6800000,
          status: 'communication',
          expectedCloseDate: '2024-10-15',
          owner: '王五',
          industry: '互联网',
          description: '优化字节跳动的广告投放系统性能',
          probability: 45,
          createdAt: '2024-07-01T14:20:00Z',
          updatedAt: '2024-07-24T09:15:00Z',
          contact: {
            name: '刘主管',
            phone: '13700137001',
            email: 'liu@bytedance.com',
            position: '技术主管',
          },
          progress: [],
        },
        {
          id: '4',
          customerName: '百度公司',
          opportunityName: 'AI模型训练平台',
          value: 15000000,
          status: 'initial',
          expectedCloseDate: '2024-11-30',
          owner: '赵六',
          industry: '互联网',
          description: '为百度AI研发团队提供模型训练基础设施',
          probability: 30,
          createdAt: '2024-07-10T16:45:00Z',
          updatedAt: '2024-07-25T10:30:00Z',
          contact: {
            name: '陈博士',
            phone: '13600136001',
            email: 'chen@baidu.com',
            position: 'AI研究员',
          },
          progress: [],
        },
      ];

      dispatch(setOpportunities(mockOpportunities));
    };

    loadOpportunities();
  }, [dispatch]);

  // 格式化货币
  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat('zh-CN', {
      style: 'currency',
      currency: 'CNY',
      minimumFractionDigits: 0,
      maximumFractionDigits: 0,
    }).format(amount);
  };

  // 获取状态显示信息
  const getStatusInfo = (status: string) => {
    const statusInfo = statusOptions.find(s => s.key === status);
    return statusInfo || { key: status, label: status, color: '#86909C' };
  };

  // 过滤商机数据
  const filteredOpportunities = opportunities.filter((opp: any) => {
    const matchesSearch = searchTerm === '' || 
      opp.opportunityName.toLowerCase().includes(searchTerm.toLowerCase()) ||
      opp.customerName.toLowerCase().includes(searchTerm.toLowerCase());
    
    const matchesStatus = statusFilter.length === 0 || statusFilter.includes(opp.status);
    const matchesIndustry = industryFilter.length === 0 || industryFilter.includes(opp.industry);
    const matchesValue = opp.value >= valueRange[0] && opp.value <= valueRange[1];

    return matchesSearch && matchesStatus && matchesIndustry && matchesValue;
  });

  // 按状态分组商机
  const groupedOpportunities = statusOptions.map(status => ({
    status: status.key,
    label: status.label,
    color: status.color,
    opportunities: filteredOpportunities.filter((opp: any) => opp.status === status.key),
  }));

  // 数据表格列定义
  const columns: TableColumnDefinition<Opportunity>[] = [
    createTableColumn<Opportunity>({
      columnId: 'customerName',
      compare: (a, b) => a.customerName.localeCompare(b.customerName),
      renderHeaderCell: () => '客户名称',
      renderCell: (item) => item.customerName,
    }),
    createTableColumn<Opportunity>({
      columnId: 'opportunityName',
      compare: (a, b) => a.opportunityName.localeCompare(b.opportunityName),
      renderHeaderCell: () => '商机名称',
      renderCell: (item) => item.opportunityName,
    }),
    createTableColumn<Opportunity>({
      columnId: 'value',
      compare: (a, b) => a.value - b.value,
      renderHeaderCell: () => '价值',
      renderCell: (item) => formatCurrency(item.value),
    }),
    createTableColumn<Opportunity>({
      columnId: 'status',
      compare: (a, b) => a.status.localeCompare(b.status),
      renderHeaderCell: () => '状态',
      renderCell: (item) => {
        const statusInfo = getStatusInfo(item.status);
        return (
          <Badge 
            appearance="filled" 
            style={{ backgroundColor: statusInfo.color, color: 'white' }}
            className={classes.statusBadge}
          >
            {statusInfo.label}
          </Badge>
        );
      },
    }),
    createTableColumn<Opportunity>({
      columnId: 'expectedCloseDate',
      compare: (a, b) => new Date(a.expectedCloseDate).getTime() - new Date(b.expectedCloseDate).getTime(),
      renderHeaderCell: () => '预计成单时间',
      renderCell: (item) => new Date(item.expectedCloseDate).toLocaleDateString('zh-CN'),
    }),
    createTableColumn<Opportunity>({
      columnId: 'owner',
      compare: (a, b) => a.owner.localeCompare(b.owner),
      renderHeaderCell: () => '负责人',
      renderCell: (item) => item.owner,
    }),
    createTableColumn<Opportunity>({
      columnId: 'actions',
      renderHeaderCell: () => '操作',
      renderCell: (item) => (
        <Menu>
          <MenuTrigger disableButtonEnhancement>
            <Button 
              appearance="subtle" 
              icon={<MoreVertical20Regular />}
              size="small"
            />
          </MenuTrigger>
          <MenuPopover>
            <MenuList>
              <MenuItem icon={<Eye20Regular />} onClick={() => navigate(`/opportunities/${item.id}`)}>
                查看详情
              </MenuItem>
              <MenuItem icon={<Edit20Regular />}>
                编辑
              </MenuItem>
              <MenuItem icon={<Delete20Regular />}>
                删除
              </MenuItem>
            </MenuList>
          </MenuPopover>
        </Menu>
      ),
    }),
  ];

  const handleNewOpportunity = () => {
    navigate('/opportunities/new');
  };

  const handleViewChange = (newView: 'list' | 'kanban') => {
    dispatch(setView(newView));
  };

  const handleCardClick = (opportunityId: string) => {
    navigate(`/opportunities/${opportunityId}`);
  };

  if (loading) {
    return (
      <div className={classes.loadingContainer}>
        <Spinner size="large" label="加载中..." />
      </div>
    );
  }

  return (
    <div className={classes.container}>
      {/* 页面头部 */}
      <div className={classes.header}>
        <h1 className={classes.title}>商机管理</h1>
        <div className={classes.actions}>
          <Button 
            appearance="secondary" 
            icon={<ArrowDownload20Regular />}
          >
            批量导入
          </Button>
          <Button 
            appearance="secondary" 
            icon={<ArrowDownload20Regular />}
          >
            导出数据
          </Button>
          <Button 
            appearance="primary" 
            icon={<Add20Regular />}
            onClick={handleNewOpportunity}
          >
            新增商机
          </Button>
        </div>
      </div>

      {/* 筛选条件 */}
      <Card className={classes.filterCard}>
        <div className={classes.filterRow}>
          <Field label="搜索">
            <Input
              placeholder="搜索商机名称或客户名称"
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              contentBefore={<Search20Regular />}
            />
          </Field>
          
          <Field label="状态筛选">
            <Dropdown
              placeholder="选择状态"
              multiselect
              value={statusFilter.join(',')}
              onOptionSelect={(_, data: any) => {
                if (data.selectedOptions) {
                  setStatusFilter(data.selectedOptions);
                }
              }}
            >
              {statusOptions.map(option => (
                <Option key={option.key} value={option.key}>
                  {option.label}
                </Option>
              ))}
            </Dropdown>
          </Field>

          <Field label="行业筛选">
            <Dropdown
              placeholder="选择行业"
              multiselect
              value={industryFilter.join(',')}
              onOptionSelect={(_, data: any) => {
                if (data.selectedOptions) {
                  setIndustryFilter(data.selectedOptions);
                }
              }}
            >
              {industryOptions.map(industry => (
                <Option key={industry} value={industry}>
                  {industry}
                </Option>
              ))}
            </Dropdown>
          </Field>

          <Field label="价值范围">
            <div className={classes.valueRangeContainer}>
              <div className={classes.valueRangeLabel}>
                {formatCurrency(valueRange[0])} - {formatCurrency(valueRange[1])}
              </div>
              <Slider
                min={0}
                max={20000000}
                step={100000}
                value={valueRange[1]}
                onChange={(_, data) => setValueRange([valueRange[0], data.value])}
              />
            </div>
          </Field>

          <div className={classes.filterActions}>
            <Button 
              appearance="secondary" 
              icon={<Filter20Regular />}
            >
              高级筛选
            </Button>
            <Button 
              appearance="subtle" 
              icon={<ArrowSync20Regular />}
              onClick={() => {
                setSearchTerm('');
                setStatusFilter([]);
                setIndustryFilter([]);
                setValueRange([0, 10000000]);
              }}
            >
              重置
            </Button>
          </div>
        </div>
      </Card>

      {/* 主要内容 */}
      <Card className={classes.contentCard}>
        {/* 内容头部 */}
        <div className={classes.contentHeader}>
          <Text>
            共找到 {filteredOpportunities.length} 个商机
          </Text>
          <div className={classes.viewToggle}>
            <ToggleButton
              checked={view === 'list'}
              icon={<List20Regular />}
              onClick={() => handleViewChange('list')}
            >
              列表视图
            </ToggleButton>
            <ToggleButton
              checked={view === 'kanban'}
              icon={<Grid20Regular />}
              onClick={() => handleViewChange('kanban')}
            >
              看板视图
            </ToggleButton>
          </div>
        </div>

        {/* 内容主体 */}
        <div className={classes.contentBody}>
          {filteredOpportunities.length === 0 ? (
            <div className={classes.emptyState}>
              <Text>暂无商机数据</Text>
            </div>
          ) : view === 'list' ? (
            // 列表视图
            <DataGrid
              items={filteredOpportunities}
              columns={columns}
              sortable
              className={classes.dataGrid}
            >
              <DataGridHeader>
                <DataGridRow>
                  {({ renderHeaderCell }) => (
                    <DataGridHeaderCell>{renderHeaderCell()}</DataGridHeaderCell>
                  )}
                </DataGridRow>
              </DataGridHeader>
              <DataGridBody<Opportunity>>
                {({ item, rowId }) => (
                  <DataGridRow<Opportunity> key={rowId}>
                    {({ renderCell }) => (
                      <DataGridCell>{renderCell(item)}</DataGridCell>
                    )}
                  </DataGridRow>
                )}
              </DataGridBody>
            </DataGrid>
          ) : (
            // 看板视图
            <div className={classes.kanbanContainer}>
              {groupedOpportunities.map(group => (
                <div key={group.status} className={classes.kanbanColumn}>
                  <div className={classes.kanbanHeader}>
                    <div className={classes.kanbanTitle}>{group.label}</div>
                    <div className={classes.kanbanCount}>{group.opportunities.length}</div>
                  </div>
                  {group.opportunities.map((opportunity: any) => (
                    <div
                      key={opportunity.id}
                      className={classes.kanbanCard}
                      onClick={() => handleCardClick(opportunity.id)}
                    >
                      <div className={classes.cardTitle}>{opportunity.opportunityName}</div>
                      <div className={classes.cardCustomer}>{opportunity.customerName}</div>
                      <div className={classes.cardValue}>{formatCurrency(opportunity.value)}</div>
                      <div className={classes.cardMeta}>
                        <span>{opportunity.owner}</span>
                        <span>{new Date(opportunity.expectedCloseDate).toLocaleDateString('zh-CN')}</span>
                      </div>
                    </div>
                  ))}
                </div>
              ))}
            </div>
          )}
        </div>

        {/* 分页 */}
        {view === 'list' && filteredOpportunities.length > 0 && (
          <div className={classes.pagination}>
            <div className={classes.paginationInfo}>
              显示 {pagination.pageSize * (pagination.page - 1) + 1}-{Math.min(pagination.pageSize * pagination.page, filteredOpportunities.length)} 条，共 {filteredOpportunities.length} 条
            </div>
            <div className={classes.paginationControls}>
              <Button
                appearance="subtle"
                disabled={pagination.page === 1}
                onClick={() => dispatch(setPagination({ page: pagination.page - 1 }))}
              >
                上一页
              </Button>
              <Text>{pagination.page}</Text>
              <Button
                appearance="subtle"
                disabled={pagination.page * pagination.pageSize >= filteredOpportunities.length}
                onClick={() => dispatch(setPagination({ page: pagination.page + 1 }))}
              >
                下一页
              </Button>
            </div>
          </div>
        )}
      </Card>
    </div>
  );
};

export default OpportunityListPage;
